import { createRouter, createWebHistory } from 'vue-router';
import Login from 'views/login/index.vue';
import Home from 'views/home/index.vue';
import subContainer from '@/components/subContainer/index.vue';
import { userState } from '@/store/module/user';
const routes = [
	{
		path: '/',
		name: 'home',
		component: Home
	},
	{
		path: '/login',
		name: 'login',
		component: Login
	},
	{
		path: '/app',
		name: 'app',
		component: Home,
		redirect: '/app',
		children: [
			{
				path: '/:pathMatch(.*)*', // 捕获所有路由或 404 Not found 路由
				component: subContainer
			}
		]
	},
	{
		// history模式需要通配所有路由，详见vue-router文档
		path: '/app/app-vue3/:pathMatch(.*)*',
		name: 'app-vue3',
		meta: {},
		component: subContainer
	},
	{
		path: '/app/app-vue2/',
		name: 'app-vue2',
		meta: {},
		component: subContainer
	}
];

const router = createRouter({
	history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? `/${name}/` : '/'),
	routes
});

//路由守卫
router.beforeEach((to, from, next) => {
	const usesStore = userState();
	const { token, menu, asyncRoutestMark } = usesStore;
	console.log('asyncRoutestMark', asyncRoutestMark);
	//如果没有token就跳转到登录
	usesStore.asyncRoutestMark = false;
	if (token) {
		if (!asyncRoutestMark) {
			menu.forEach(() => {
				menu.childs &&
					menu.childs.forEach((item) => {
						router.addRoute('app', {
							path: `/${item.id}`,
							meta: { name: item.name, isAsync: true, icon: item.icon },
							name: item.id,
							component: subContainer
						});
					});
			});
			usesStore.asyncRoutestMark = true; // 添加路由后更改标识为true
			next({ ...to, replace: true });
		} else {
			next();
		}
	} else {
		if (to.path === '/login') {
			next();
		} else {
			next('/login');
		}
	}
});
export default router;
